package com.zbcz.erp.adapter

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.OpenableColumns
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.zbcz.erp.R
import com.zbcz.erp.activity.ErpWorkProcessActivity
import com.zbcz.erp.activity.FullScreenImageViewActivity
import com.zbcz.erp.activity.FullScreenImageViewActivity.Companion.IMAGE_URL
import com.zbcz.erp.activity.PdfPreViewActivity
import com.zbcz.erp.activity.PdfPreViewActivity.Companion.LOCAL_URL
import com.zbcz.erp.activity.PdfPreViewActivity.Companion.REMOTE_URL
import com.zbcz.erp.bean.FileItem
import com.zbcz.erp.databinding.ItemEditFileBinding
import com.zbcz.erp.databinding.ItemFileChooseBinding
import com.zbcz.erp.network.RetrofitManager
import com.zbcz.erp.util.ToastUtils
import com.zbcz.erp.util.onSingleClick
import com.zbcz.erp.util.openDocumentsFilePicker
import java.io.File
import java.io.FileOutputStream

class CommonEditFileAdapter(
    private val activity: Activity,
) : ListAdapter<FileItem, RecyclerView.ViewHolder>(FileDiffCallback()) {


    companion object {
        const val FILE_TYPE = 0
        const val REMOTE_FILE_TYPE = 2
        const val ADD_FILE_TYPE = -1
        const val MAX_SIZE = 1
        const val TAG = "CommonEditFileAdapter"
    }


    override fun getItemViewType(position: Int): Int {
        return getItem(position).type
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        when (viewType) {
            FILE_TYPE, REMOTE_FILE_TYPE -> {
                val view =
                    ItemEditFileBinding.inflate(LayoutInflater.from(parent.context), parent, false)
                return FileViewHolder(view)
            }

            else -> {
                val view = ItemFileChooseBinding.inflate(
                    LayoutInflater.from(parent.context), parent, false
                )
                return AddFileHolder(view)
            }
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val fileItem = getItem(position)
        if (holder is FileViewHolder) {
            holder.bind(fileItem)
        } else if (holder is AddFileHolder) {
            holder.bind()
        }
    }


    inner class AddFileHolder(binding: ItemFileChooseBinding) :
        RecyclerView.ViewHolder(binding.root) {
        init {
            binding.root.onSingleClick {
                if (currentList.size >= MAX_SIZE + 1) {
                    ToastUtils.show("最多上传" + MAX_SIZE + "个文件")
                    return@onSingleClick
                }
                openDocumentsFilePicker(
                    activity, ErpWorkProcessActivity.REQUEST_CODE_OPEN_DOCUMENT
                )
            }
        }

        fun bind() {

        }
    }


    inner class FileViewHolder(private val binding: ItemEditFileBinding) :
        RecyclerView.ViewHolder(binding.root) {

        init {
            binding.root.onSingleClick {

            }

            binding.ivDelIcon.onSingleClick {
                val position = adapterPosition
                if (position != RecyclerView.NO_POSITION) {
                    val currentList = currentList.toMutableList()
                    currentList.removeAt(position)
                    submitList(currentList)
                }
            }
        }

        fun bind(fileItem: FileItem) {
            binding.ivDelIcon.visibility = if (fileItem.isDelAble) View.VISIBLE else View.GONE
            if (fileItem.type == FILE_TYPE) {
                val targetFileName = fileItem.uri?.let { getFileNameFromUri(it, activity) }
                binding.title.text = targetFileName
                Log.i(TAG, "targetFile=$targetFileName")
                val context = binding.root.context
                when (targetFileName?.substringAfterLast(".")) {
                    "doc", "docx" -> {
                        binding.ivIcon.setImageResource(R.drawable.file_type_word)
                    }

                    "pdf" -> {
                        binding.ivIcon.setImageResource(R.drawable.file_type_pdf)
                        binding.ivIcon.onSingleClick {
                            context.startActivity(Intent(
                                context, PdfPreViewActivity::class.java
                            ).apply {
                                putExtra(LOCAL_URL, fileItem.uri.toString())
                            })
                        }
                    }

                    "excel" -> {
                        binding.ivIcon.setImageResource(R.drawable.file_type_excel)
                    }

                    "jpg", "png", "jpeg" -> {
                        Glide.with(binding.root.context).load(fileItem.uri).into(binding.ivIcon)
                        binding.ivIcon.onSingleClick {
                            binding.root.context.startActivity(Intent(
                                binding.root.context, FullScreenImageViewActivity::class.java
                            ).apply {
                                putExtra(IMAGE_URL, fileItem.uri.toString())
                            })
                        }
                    }

                    else -> binding.ivIcon.setImageResource(R.drawable.default_icon)
                }
            } else if (fileItem.type == REMOTE_FILE_TYPE) {
                val exTensionFileName = fileItem.remoteUrl.substringAfterLast(".")
                when (exTensionFileName) {
                    "jpg", "png", "jpeg" -> {
                        Glide.with(binding.root.context)
                            .load(RetrofitManager.getFileAddress(fileItem.remoteUrl))
                            .into(binding.ivIcon)
                        binding.ivIcon.onSingleClick {
                            binding.root.context.startActivity(Intent(
                                binding.root.context, FullScreenImageViewActivity::class.java
                            ).apply {
                                putExtra(
                                    IMAGE_URL,
                                    RetrofitManager.getFileAddress(fileItem.remoteUrl)
                                )
                            })
                        }
                    }

                    "pdf" -> {
                        binding.ivIcon.setImageResource(R.drawable.file_type_pdf)
                        binding.ivIcon.onSingleClick {
                            binding.root.context.startActivity(Intent(
                                binding.root.context, PdfPreViewActivity::class.java
                            ).apply {
                                putExtra(
                                    REMOTE_URL,
                                    RetrofitManager.getFileAddress(fileItem.remoteUrl)
                                )
                            })
                        }
                    }
                }
                binding.title.text = fileItem.remoteUrl
            }
        }
    }

    class FileDiffCallback : DiffUtil.ItemCallback<FileItem>() {
        override fun areItemsTheSame(oldItem: FileItem, newItem: FileItem): Boolean {
            return oldItem.uri == newItem.uri
        }

        override fun areContentsTheSame(oldItem: FileItem, newItem: FileItem): Boolean {
            return oldItem == newItem
        }
    }

    fun addData(item: FileItem?) {
        val currentList = currentList.toMutableList()
        currentList.add(item)
        submitList(currentList)
    }

    fun addData(item: Uri?) {
        val currentList = currentList.toMutableList()
        if (currentList.size >= MAX_SIZE + 1) {
            ToastUtils.show("最多上传" + MAX_SIZE + "个文件")
            return
        }
        currentList.add(FileItem(item, FILE_TYPE, isDelAble = true))
        submitList(currentList)
    }

    fun getFileNameFromUri(uri: Uri, context: Context): String {
        var fileName = "Unknown"
        context.contentResolver.query(uri, null, null, null, null)?.use { cursor ->
            if (cursor.moveToFirst()) {
                val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
                if (nameIndex >= 0) {
                    fileName = cursor.getString(nameIndex)
                }
            }
        }
        //fileName.substringBeforeLast(".")
        return fileName
    }

    fun getExtensionNameFromUri(uri: Uri, context: Context): String {
        var fileName = "Unknown"
        context.contentResolver.query(uri, null, null, null, null)?.use { cursor ->
            if (cursor.moveToFirst()) {
                val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
                if (nameIndex >= 0) {
                    fileName = cursor.getString(nameIndex)
                }
            }
        }
        return fileName.substringAfterLast(".")
    }

    /**
     * 当有本地文件时
     */
    fun getTargetFile(context: Context): File? {
        val list = currentList.filter {
            it.type == FILE_TYPE
        }
        if (list.size == 1) {
            list[0].let { fileItem ->
                fileItem?.uri?.let { uri ->
                    return getFileFromUri(context, uri, getFileNameFromUri(uri, context))
                }
            }
        }
        return null
    }

    private fun getFileFromUri(context: Context, uri: Uri, extensionName: String): File? {
        return when (uri.scheme) {
            "file" -> {
                // 对于 file:// URI，直接返回对应的 File 对象
                val path = uri.path ?: return null
                File(path)
            }

            "content" -> {
                // 对于 content:// URI，尝试将数据复制到应用的私有存储
                try {
                    val inputStream = context.contentResolver.openInputStream(uri) ?: return null
                    val fileName = "${System.currentTimeMillis()}.$extensionName" // 临时文件名，可以根据需要调整
                    val file = File(context.filesDir, fileName)

                    // 将内容写入到文件
                    inputStream.use { input ->
                        FileOutputStream(file).use { output ->
                            input.copyTo(output)
                        }
                    }

                    // 返回新创建的 File 对象
                    file
                } catch (e: Exception) {
                    e.printStackTrace()
                    null
                }
            }

            else -> {
                // 不支持的 URI scheme
                null
            }
        }
    }

}
